﻿using System;

namespace UnityEngine.Extension
{
    public static class ComponentExtension
    {
        public static void ForEachChild(this Component source, Action<GameObject, string> callBack)
        {
            int maxCount = source.transform.childCount;
            for (int i = 0; i < maxCount; i++)
            {
                Transform child = source.transform.GetChild(i);
                string path = child.name;
                callBack(child.gameObject, path);
                child.ForEachChild((c, s) => callBack(c.gameObject, path += ("/" + c.name)));
            }
        }

        public static void ForEachChild<T>(this Component source, Action<T, string> callBack) where T : Component
        {
            source.ForEachChild((child, path) => {
                T[] components = child.GetComponents<T>();
                foreach (T component in components)
                    callBack(component, path + "/" + component.GetType().Name);
            });
        }

        public static void ForEachComponent<T>(this UnityEngine.Object source, Action<T> callBack) where T : Component
        {
            if (source is GameObject)
            {
                GameObject gameObject = source as GameObject;
                T[] components = gameObject.GetComponents<T>();
                foreach (T component in components)
                    callBack(component);
            }
        }
    }
}